package com.ttfeed.server.common.config;

import com.alibaba.fastjson2.support.spring.data.redis.FastJsonRedisSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisTemplateService {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 批量删除对应的value
     *
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 批量删除key
     *
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<String> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0) {
            redisTemplate.delete(keys);
        }
    }

    /**
     * 删除对应的value
     *
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<String, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<String, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public boolean set(final String key, Object value, Integer expireTime, TimeUnit timeUnit) {
        boolean result = false;
        try {
            ValueOperations<String, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, timeUnit);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 访问控制
     *
     * @param key   指定redis key
     * @param count 指定访问的次数
     * @param times 指定时间周期(以秒为单位)
     * @return
     */
    public boolean ifAllowed(String key, long count, long times) {
        boolean flag = true;

        ValueOperations<String, Object> operations = redisTemplate.opsForValue();

        if (exists(key)) {
            // key对应的value自加1
            Long l = operations.increment(key, 1L);

            try {
                // 访问次数超过规定，则不允许访问
                if (l > count) {
                    flag = false;
                }
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        } else {
            // 第一次访问，设置初始值1
            set(key, 1, times);
        }

        return flag;
    }

    /**
     * 对应的key 自增
     *
     * @param key value 初始的值
     */
    public Long increment(String key, Long value, long times) {
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        if (exists(key)) {
            // key对应的value自加1
            Long count = operations.increment(key, 1L);
            if (times > 0) {
                expire(key, times);
            }
            return count;
        } else {
            // 第一次访问，设置初始值1
            set(key, 1L);
            if (times > 0) {
                expire(key, times);
            }
        }
        if (value != null) {
            set(key, value);
        }
        return null;
    }

    /**
     * 对应的key 自增
     *
     * @param key value 初始的值
     */
    @Deprecated
    public Long increment(String key, Long value) {
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();

        if (exists(key)) {
            // key对应的value自加1
            Long count = operations.increment(key, 1L);
            return count;
        } else {
            // 第一次访问，设置初始值1
            set(key, 1L);
        }
        if (value != null) {
            set(key, value);
        }
        return null;
    }

    /**
     * 对应的key 减少
     *
     * @param key
     */
    public Long reduce(String key) {
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        if (exists(key)) {
            // key对应的value自加1
            Long count = operations.increment(key, -1L);
            return count;
        }
        return null;
    }

    /**
     * 获取缓存set数据
     *
     * @param k
     * @return
     */
    public Set<Object> getSet(String k) {
        SetOperations<String, Object> setOps = redisTemplate.opsForSet();
        return setOps.members(k);
    }

    /**
     * 进行set类型的缓存
     *
     * @param k
     * @param v
     * @return
     */
    public boolean cacheSet(String k, Set<Object> v) {
        SetOperations<String, Object> setOps = redisTemplate.opsForSet();
        setOps.add(k, v.toArray(new Object[0]));
        return true;
    }

    public boolean cacheSet(String k, Long v) {
        SetOperations<String, Object> setOps = redisTemplate.opsForSet();
        setOps.add(k, v);
        return true;
    }

    /**
     * HashGet
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 获取hashKey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<Object, Object> hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     *
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
    public boolean hmset(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * HashSet 并设置时间
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public boolean hmset(String key, Map<String, Object> map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取Hash表size
     *
     * @param key
     * @return
     */
    public int hlength(String key) {
        try {
            HashOperations<String, String, Object> oper = redisTemplate.opsForHash();
            return oper.size(key).intValue();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }

    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * 设置缓存失效的时间
     *
     * @param k
     * @param d
     * @return
     */
    public boolean expireDate(String k, Date d) {
        return Boolean.TRUE.equals(redisTemplate.expireAt(k, d));
    }

    /**
     * key 延期
     *
     * @param k
     * @param l
     * @return
     */
    public boolean expire(String k, Long l) {
        return Boolean.TRUE.equals(redisTemplate.expire(k, l, TimeUnit.SECONDS));
    }

    /**
     * 删除key
     *
     * @param k
     * @return
     */
    public boolean deleteKey(String k) {
        redisTemplate.delete(k);
        return true;
    }

    /**
     * 指定时间类型---秒
     *
     * @param key
     * @return
     */
    public long getExpireTimeType(String key) {
        Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
        return expire == null ? 0 : expire;
    }

    public Set sMember(String key, Long timeOut) {
        Set set = redisTemplate.opsForSet().members(key);
        if (timeOut != null && timeOut > 0) {
            redisTemplate.expire(key, timeOut, TimeUnit.SECONDS);
        }
        return set;
    }

    public Long sAdd(String key, Long timeOut, Object... items) {
        Long result = redisTemplate.opsForSet().add(key, items);
        if (timeOut != null && timeOut > 0) {
            redisTemplate.expire(key, timeOut, TimeUnit.SECONDS);
        }
        return result;
    }

    public Long sRem(String key, Object... objects) {
        return redisTemplate.opsForSet().remove(key, objects);
    }

    /**
     * 查询所有的key
     *
     * @param pattern
     * @return
     */
    public Set<String> keys(String pattern) {
        return redisTemplate.keys(pattern);
    }

    @SuppressWarnings("unchecked")
    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        //使用fastjson序列化
        FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);

        // value值的序列化采用fastJsonRedisSerializer
        redisTemplate.setValueSerializer(fastJsonRedisSerializer);
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        // key的序列化采用StringRedisSerializer
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        this.redisTemplate = redisTemplate;
    }


}

